package novel.mzx.com.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import novel.mzx.com.R;
import novel.mzx.com.adapter.GridImageAdapter;
import novel.mzx.com.base.BaseActivity;
import novel.mzx.com.bean.CodeBean;
import novel.mzx.com.bean.SuccessBean;
import novel.mzx.com.bean.TypeBean;
import novel.mzx.com.http.Api;
import novel.mzx.com.http.SpDataUtils;
import novel.mzx.com.utils.JSONUtils;
import novel.mzx.com.utils.PermissionsUtil;
import novel.mzx.com.utils.StringUtils;
import novel.mzx.com.utils.TimeUtil;
import novel.mzx.com.utils.ToastUtils;
import novel.mzx.com.utils.Util;
import novel.mzx.com.views.FullyGridLayoutManager;

/**
 * 添加文章界面
 *    * 实现了util包下的一些接口
 *    * 主要实现是通过实现picture_library包下的API完成读取相册图片，上传图片的操作
 * */
public class AddCircleActivity extends BaseActivity implements PermissionsUtil.IPermissionsCallback {

    //  @BindView简化了绑定 EditText控件 的过程
    @BindView(R.id.et_01)
    EditText et_01;

    @BindView(R.id.btn_02)
    Button btn_02;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;


    @BindView(R.id.iv_back)
    ImageView iv_back;

    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private List<File> list = new ArrayList<>();
    private List<String> listPath = new ArrayList<>();

    @Override
    protected int getResourceId() {
        return R.layout.activity_add_circle;
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this).titleBar(R.id.toolbar).keyboardEnable(true).init();
        ImmersionBar.with(this).keyboardEnable(false).statusBarDarkFont(true, 0.2f).navigationBarColor(R.color.btn3).init();

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        /**
         * 初始化一些适配器和布局管理
         * */
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(1);
        recyclerView.setAdapter(adapter);

        btn_02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String content = et_01.getText().toString().trim();
                if(content.equals("")){
                    ToastUtils.showToast(AddCircleActivity.this,"请输入内容!");
                    return;
                }

                if(list.size() > 0){
                    File file = list.get(0);

                    showDialog("正在上传，请稍后...");
                    OkGo.<String>post(Api.mainHost+ Api.photoUploadUrl)
                            .tag(this)
                            .params("file", file)
                            .isMultipart(true)
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    Log.e("上传照片成功!",response.body());
                                    SuccessBean getServiceImgBean = JSONUtils.parserObject(response.body(), SuccessBean.class);
                                    if (getServiceImgBean.getResultCode() == 200){
                                        gettImgUrl(getServiceImgBean.getData());
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {

                                }
                            });

                }else {

                    getNoImgUrl();
                }
            }
        });



    }



    private void gettImgUrl(String data) {
        File file = list.get(0);

        OkGo.<String>post(Api.mainHost+ Api.addCircleInfoUrl)
                .tag(this)
                .isMultipart(true)
                .params( "picture",file )
                //.params("jzCircleFile",data)
                .params("jzCircleContent", StringUtils.getEditTextData(et_01))
                .params("jzCircleUsername", SpDataUtils.getUserName())
                .params("jzCircleAccount", SpDataUtils.getAccount())
                .params("jzCircleLogo", SpDataUtils.getUserLogo())
                .params("jzCircleTime", TimeUtil.getNowTime())
                .execute(new StringCallback(){
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("添加分享",response.body());
                        stopDialog();
                        CodeBean codeBean = JSONUtils.parserObject(response.body(), CodeBean.class);
                        int code = codeBean.getResultCode();
                        if(code == 200){
                            ToastUtils.showToast(AddCircleActivity.this,"分享成功!");
                            Intent intent = new Intent();
                            intent.setAction("freshCircle");
                            sendBroadcast(intent);
                            finish();
                        }else {
                            ToastUtils.showToast(AddCircleActivity.this,"分享失败!");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.showToast(getApplicationContext(),"找不到服务器了，请稍后再试");
                    }
                });

    }

    private void getNoImgUrl() {
        OkGo.<String>get(Api.mainHost+ Api.addCircleInfoUrl)
                .params("jzCircleContent", StringUtils.getEditTextData(et_01))
                .params("jzCircleUsername", SpDataUtils.getUserName())
                .params("jzCircleAccount", SpDataUtils.getAccount())
                .params("jzCircleLogo", SpDataUtils.getUserLogo())
                .params("jzCircleTime", TimeUtil.getNowTime())
                .params("className", SpDataUtils.getClassName())
                .params("majorName", SpDataUtils.getMajorName())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("添加分享",response.body());

                        CodeBean codeBean = JSONUtils.parserObject(response.body(), CodeBean.class);
                        int code = codeBean.getResultCode();
                        if(code == 200){
                            ToastUtils.showToast(AddCircleActivity.this,"分享成功!");
                            Intent intent = new Intent();
                            intent.setAction("freshCircle");
                            sendBroadcast(intent);
                            finish();
                        }else {
                            ToastUtils.showToast(AddCircleActivity.this,"分享失败!");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });
    }



    @Override
    protected void onResume() {
        super.onResume();

    }


    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(AddCircleActivity.this)
                    .openGallery(PictureMimeType.ofAll())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(1)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(true)// 是否可预览视频
                    .enablePreviewAudio(false) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    //.compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    //.withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                    //.isGif(cb_isGif.isChecked())// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .openClickSound(false)// 是否开启点击声音
                    .selectionMedia(selectList)// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    .recordVideoSecond(60)//录制视频秒数 默认60s
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };


    private String choose_type = "";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList.clear();
                    list.clear();
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    listPath.clear();
                    for (LocalMedia media : selectList) {
                        Log.e("图片-----》", media.getPath());
                        File file = new File(media.getPath());
                        list.add(file);
                        listPath.add(media.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, String... permission) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, String... permission) {

    }



}
